import matplotlib
from matplotlib.mathtext import MathTextParser
import tempfile

from pod.std import *
from pod.macros.html.util import tag, css

class Equation(Macro):
    name="eqn"
    doctype = "html"
    
    counter = 0
    parser = MathTextParser("Bitmap")
    
    def __init__(self, ctx, label=None, inline=True):
        super(Equation, self).__init__()
        self.label = label
        self.inline = inline
        
        if self.label: env["label:%s" % self.label] = self
        
        if self.inline:
            self.dpi = ctx.env.get("equations.dpi.inline", 100)
        else:
            self.dpi = ctx.env.get("equations.dpi", 120)
        #endif
            
        self.number = Equation.counter
        Equation.counter += 1
        
    def createEquation(self, filename):
        table = tag("table", klass="equation")[
            tag("tr", klass="equation")[
                tag("td", klass="equation")[
                    tag("img", src="%s" % filename)
                ],
                tag("td", klass="equation_number")[
                    tag("b")["(%d)" % self.number]
                ]
            ]
        ]
        return str(table)
    
    def __call__(self, content):
        with open("equation_%d.png" % self.number, "w")  as output:
            Equation.parser.to_png(output, "$%s$" % Macro.flatten(content), dpi=self.dpi)
            if not self.inline: return self.createEquation(output.name)
            return '<img src="%s" class="inline_equation">' % output.name
